package org.ioriframework.boot.job.listener;

import java.util.List;

import javax.annotation.Resource;

import org.ioriframework.boot.core.request.impl.RequestContextManager;
import org.ioriframework.boot.core.util.CollectionUtils;
import org.ioriframework.boot.job.service.JobService;
import org.ioriframework.boot.job.trigger.JobTrigger;
import org.ioriframework.boot.job.vo.JobVO;
import org.ioriframework.boot.register.IRegisterProperty;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 定时任务启动监听器
 * 1. 平台启动后，将工厂中不存在的任务改为失效状态
 * 2. 重启之前是运行中的所有任务（默认重启，可通过数据字典配置为不重启）
 * @author iori
 *
 */
@Component
public class JobApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent>, Ordered {

	private static Logger log = LoggerFactory.getLogger(JobApplicationReadyListener.class);
	
	@Autowired
	private JobService jobService;
	
	@Autowired
	private JobTrigger jobTrigger;
	
	@Resource
	private IRegisterProperty registerProperty;

	@Override
	public void onApplicationEvent(ApplicationReadyEvent event) {
		log.info("Init Job start...");
		try {
			List<JobVO> jobList = jobService.findJobList4Resume();
			if (!CollectionUtils.isNullOrEmpty(jobList)) {
				// 初始化系统用户上下文, -1代表是系统用户
				RequestContextManager.initSystemUserRC(-1L);
				// 通过数据字典获取是否重启失效状态的任务，默认为重启
				int resumeJob = Integer.valueOf(registerProperty.findRegisterValue("Iori.GlobalParamsters.ResumeJob", "1"));
				for (JobVO jobVO : jobList) {
					// 当前任务状态
					int preStatus = jobVO.getStatus();
					// 如果任务在工厂中不存在
					if (!jobTrigger.checkExists(jobVO)) {
						// 更新任务状态为失效
						jobVO.setStatus(0);
						jobService.updateJobStatus(jobVO);
						log.debug("Job[{}] set invalid success.", new Object[] {jobVO.getJobName() + "." + jobVO.getGroupName()});
					}
					// 设置了重启任务，并且任务之前是运行中的
					if (resumeJob == 1 && preStatus == 1) {
						try {
							// 重启任务
							jobTrigger.resumeJob(jobVO);
							// 更新任务状态为运行中
							jobVO.setStatus(1);
							jobService.updateJobStatus(jobVO);
							log.debug("Job[{}] resume success.", new Object[] {jobVO.getJobName() + "." + jobVO.getGroupName()});
						} catch (SchedulerException e) {
							log.error("Job[{}] resume failed. error: {}", new Object[] {jobVO.getJobName() + "." + jobVO.getGroupName(), e.getMessage()});
						}
					}
				}
			}
		} catch (Exception e) {
			log.error("Init Job failed. error: ", e);
		}
		log.info("Init Job end.");
		
	}

	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE-2;
	}
	
}
